<template>
  <BasicModal
    v-bind="$attrs"
    width="500px"
    :title="!unref(isUpdateRef) ? '新增用户类型' : '编辑用户类型'"
    showFooter
    @register="registerWindow"
    @ok="submitForm"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModal } from '@/components/Modal';
  import { FormSchema } from '@/components/Table';

  import userTypeApi from '@/api/user/userTypeApi';
  import UserRequest from '@/api/model/UserRequest';

  // 是否是 update 窗口
  const isUpdateRef = ref(true);

  // 表单绑定 model
  const formModel = ref<any>({});

  // 定义表单列
  const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: '用户类型',
      component: 'Input',
      required: true,
    },
    {
      field: 'status',
      label: '状态',
      component: 'RadioGroup',
      defaultValue: 0,
      componentProps: {
        options: [
          { label: '启用', value: 1 },
          { label: '停用', value: 0 },
        ],
      },
    },
    {
      label: '备注',
      field: 'remark',
      component: 'InputTextArea',
      componentProps: {
        autoSize: {
          minRows: 2,
          maxRows: 5,
        },
      },
    },
  ];

  // 注册表单
  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    model: formModel,
  });

  // 注册窗口
  const [registerWindow, { openModal, closeModal, setModalProps }] = useModal();

  // 打开窗口
  function open(isUpdate: boolean, record?: UserRequest) {
    isUpdateRef.value = isUpdate;
    // 更新则初始化表单
    if (isUpdate) {
      formModel.value = record;
    } else {
      resetFields();
    }

    // 打开窗口
    openModal();
  }

  // 接收回调
  const emit = defineEmits(['success']);
  async function submitForm() {
    try {
      const values: UserRequest = await validate();
      // 确定按钮显示 loading 效果
      setModalProps({ confirmLoading: true });

      // 执行新增或更新操作
      if (isUpdateRef.value) {
        await userTypeApi.update(formModel.value.id, values);
      } else {
        await userTypeApi.save(values);
      }

      closeModal();
      emit('success');
    } finally {
      // 关闭按钮 loading
      setModalProps({ confirmLoading: false });
    }
  }

  // 对父组件暴露 open 方法
  defineExpose({ open });
</script>
